<script setup lang="ts">
  import { onMounted, ref } from 'vue';
  import { ElMenu, ElSubMenu, ElMenuItem, ElInput, ElMessage } from 'element-plus';
  import { getRelationByFrom, saveAsset, saveRelation } from '/@/api/thingsborad/entity/entity';
  import {
    relationResponse,
    saveAssetParams,
    saveRelationParams,
  } from '/@/api/thingsborad/entity/model/entityModel';
  import sendToUnity from '/@/core/communication/SendToUnity';
  import { SendMessageType, Platform } from '/@/config/DeclareGlobal';
  import {FileLoadUrl} from "/@/core/communication/interface/ISendUnity";

  const searchQuery = ref<string>('');

  const createFolder = () => {
    console.log('Create new folder');
  };
  // 直接使用 relationResponse 类型
  const relationItems = ref<relationResponse>();
  const selectedItemId = ref('');
  const myResourceName = ref<relationResponse>();
  // 加载关联数据
  onMounted(() => {
    getRelationByFrom({
      fromId: '817f0200-05fb-11f0-9456-7394060ad530',
      fromType: 'ASSET',
    }).then((response) => {
      myResourceName.value = findFirstItemByToName(response, '我的资源-模型-我的资源');
      console.log(myResourceName);
      console.log(response);
    });
    getRelationByFrom({
      fromId: '46eed2a0-0a0b-11f0-9456-7394060ad530',
      fromType: 'ASSET',
    }).then((response) => {
      relationItems.value = response;
    });
  });
  function findFirstItemByToName(
    items: relationResponse[],
    targetName: string,
  ): relationResponse | undefined {
    return items.find((item) => item.toName === targetName);
  }

  // 点击菜单项时触发
  const handleItemClick = (item) => {
    selectedItemId.value = item.from.id;
    const filename = item.toName;
    sendMessageToUnity(filename);
  };

  const sendMessageToUnity = (filename) => {
    // 发送消息
    sendToUnity.send({
      type: SendMessageType.LoadModel,
      data: {
        url: `${FileLoadUrl}download/`,
        filename: filename,
      },
      platform: Platform.web2unity,
    });
  };
  const formatName = (name: string | undefined) => {
    if (!name) return ''; // 处理 undefined 或空值
    const index = name.lastIndexOf('-');
    return index !== -1 ? name.slice(index + 1) : name;
  };
  // 弹窗控制函数
  function showModal() {
    const modal = document.getElementById('modal');
    if (modal) modal.style.display = 'flex';
  }

  function hideModal() {
    const modal = document.getElementById('modal');
    if (modal) modal.style.display = 'none';
  }

  // 点击背景关闭
  window.addEventListener('click', (e) => {
    const modal = document.getElementById('modal');
    if (e.target === modal) {
      hideModal();
    }
  });

  const fileInput = ref<HTMLInputElement | null>(null);
  const progress = ref(0);
  const statusMessage = ref('');
  // 核心上传方法
  const uploadFile = async () => {
    try {
      if (!fileInput.value?.files?.length) {
        statusMessage.value = '请先选择文件';
        return;
      }
      const file = fileInput.value.files[0];

      // 重置进度
      progress.value = 0;

      const uploadedFilename = await uploadToServer(file);
      const encodedFilename = encodeURIComponent(uploadedFilename);
      const downloadUrl = `http://localhost:8089/download/${encodedFilename}`;

      await saveData(uploadedFilename, downloadUrl);
      statusMessage.value = '文件上传并加载成功！';
    } catch (error) {
      statusMessage.value = `操作失败`;
    } finally {
      // 可选：上传完成后延迟重置进度
      setTimeout(() => {
        progress.value = 0;
      }, 2000);
    }
  };

  // 文件上传函数
  const uploadToServer = async (file: File): Promise<string> => {
    const formData = new FormData();
    formData.append('file', file);

    return new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();

      // 监听上传进度
      xhr.upload.onprogress = (event) => {
        if (event.lengthComputable) {
          const percentCompleted = Math.round((event.loaded * 100) / event.total);
          progress.value = percentCompleted; // 更新进度条
        }
      };

      // 请求完成时的处理
      xhr.onload = () => {
        if (xhr.status >= 200 && xhr.status < 300) {
          const response = JSON.parse(xhr.responseText);
          resolve(response.filename); // 返回带时间戳前缀的文件名
        } else {
          reject(new Error('文件上传失败'));
        }
      };

      // 请求出错时的处理
      xhr.onerror = () => {
        reject(new Error('网络错误'));
      };

      // 发起 POST 请求
      xhr.open('POST', 'http://localhost:8089/api/upload', true);
      xhr.send(formData);
    });
  };

  // 保存数据
  const saveData = async (filename: string, url: string) => {
    const assetParams: saveAssetParams = {
      name: filename,
      assetProfileId: {
        entityType: 'ASSET_PROFILE',
        id: 'e0af0500-ffd8-11ef-9a2b-831759278053',
      },
      customerId: null,
      additionalInfo: {
        description: url,
      },
    };

    try {
      // 保存资产
      const asset = await saveAsset(assetParams);

      // 创建关联
      const relationParams: saveRelationParams = {
        type: 'Contains',
        additionalInfo: {},
        typeGroup: 'COMMON',
        from: {
          entityType: 'ASSET',
          id: '46eed2a0-0a0b-11f0-9456-7394060ad530',
        },
        to: asset.id,
      };
      // 保存关联
      await saveRelation(relationParams);
    } catch (error) {
      throw new Error(`操作失败：${error}`);
    }
  };
  const downloadFile = async () => {
    try {
      // 获取用户输入的文件名
      const filenameInput = document.getElementById('filename') as HTMLInputElement;
      const filename = filenameInput!.value.trim();

      if (!filename) {
        alert('请输入要下载的文件名');
        return;
      }

      // 构造下载 URL
      const encodedFilename = encodeURIComponent(filename);
      const downloadUrl = `http://localhost:8089/download/${encodedFilename}`;

      // 触发下载
      const a = document.createElement('a');
      a.href = downloadUrl;
      a.download = filename; // 设置下载的文件名
      document.body.appendChild(a); // 将 <a> 标签添加到 DOM 中
      a.click(); // 模拟点击
      document.body.removeChild(a); // 移除 <a> 标签
    } catch (error) {
      console.error('下载失败:', error);
      alert('下载失败，请稍后重试');
    }
  };
</script>

<template>
  <div class="model-view">
    <!-- 左侧导航栏容器 -->
    <div class="menu-container">
      <!-- 搜索框 -->
      <el-input v-model="searchQuery" placeholder="搜索..." class="search-box" />
      <!-- 新建文件夹按钮 -->
      <div class="create-folder" @click="createFolder">+ 新建文件夹</div>
      <!-- 弹窗 -->
      <div id="modal" class="modal">
        <div class="modal-content">
          <span class="close" @click="hideModal">&times;</span>
          <div class="container">
            <h2>文件上传测试</h2>
            <div class="upload-box">
<!--              <input type="file" ref="fileInput" id="fileInput" accept=".fbx,.txt,.jpg" />-->
              <button @click="uploadFile()">上传文件</button>
              <div class="progress-bar">
                <div class="progress" :style="{ width: progress + '%' }"></div>
              </div>
              <div id="status" class="status">{{ statusMessage }}</div>
            </div>

            <div class="download-box">
              <h3>下载测试</h3>
              <input type="text" id="filename" placeholder="输入要下载的文件名" />
              <button @click="downloadFile()">下载文件</button>
            </div>
          </div>
        </div>
      </div>
      <!-- 导航栏 -->
      <el-menu
        background-color="#1e2430"
        text-color="#fff"
        active-text-color="#ffd04b"
        class="side-bar"
      >
        <el-sub-menu index="my-resources" key="my-resources">
          <template #title>
            <span>{{ formatName(myResourceName) }}</span>
          </template>
          <div class="upload-file" @click="showModal">+ 上传文件</div>
          <el-menu-item
            v-for="item in relationItems"
            :key="item.to.id"
            :index="item.to.id"
            @click="handleItemClick(item)"
            :class="{ 'is-active': selectedItemId === item.to.id }"
          >
            {{ formatName(item.toName) }}
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </div>
  </div>
</template>

<style scoped>
  :deep(.el-input__wrapper) {
    background-color: gray !important;
    box-shadow: none;
  }

  .model-view {
    height: 100%;
    display: flex;
    align-items: flex-start;
  }

  .menu-container {
    height: 95vh;
    width: 14vw; /* 确保宽度与 .side-bar 一致 */
    display: flex;
    flex-direction: column;
  }

  .search-box {
    margin-bottom: 0; /* 调整搜索框与菜单之间的间距 */
    padding: 5px; /* 添加内边距 */
    border: none; /* 去掉边框 */
    background-color: #1e2430; /* 设置背景颜色为灰色 */
    color: #fff; /* 设置文字颜色为白色 */
  }

  /* 新增样式以去除中间的白色空隙并设置淡灰色背景 */
  .search-box .el-input__inner {
    background-color: #474e5b; /* 淡灰色背景 */
    border: none;
    height: 32px; /* 调整高度以匹配默认样式 */
  }

  .side-bar {
    flex-grow: 1; /* 让 el-menu 占据剩余空间 */
    width: 100%;
    margin-right: 20px;
  }

  .create-folder {
    padding-left: 0.8vw;
    height: 3vh;
    background-color: #1e2430;
    cursor: pointer;
    color: rgb(69, 131, 255); /* 默认字体颜色为蓝色 */
    font-size: 0.8vw;
    text-decoration: none; /* 默认没有下划线 */
  }

  .create-folder:hover {
    text-decoration: underline; /* 鼠标悬浮时添加下划线 */
  }
  .upload-file {
    padding-left: 1.2vw;
    height: 3vh;
    background-color: #1e2430;
    cursor: pointer;
    color: rgb(69, 131, 255); /* 默认字体颜色为蓝色 */
    font-size: 0.8vw;
    text-decoration: none; /* 默认没有下划线 */
  }
  .upload-file:hover {
    text-decoration: underline; /* 鼠标悬浮时添加下划线 */
  }
  .main-content {
    flex-grow: 1;
    padding: 0;
  }
  .el-menu-item.is-active {
    color: white;
  }
  /* 弹窗样式 */
  .modal {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    justify-content: center;
    align-items: center;
    z-index: 999;
  }

  .modal-content {
    background: white;
    padding: 20px;
    border-radius: 8px;
    min-width: 400px;
    position: relative;
  }

  .close {
    position: absolute;
    right: 15px;
    top: 10px;
    cursor: pointer;
    font-size: 24px;
  }
  button {
    padding: 1vh 1vw;
    background: #2196f3;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }

  button:hover {
    background: #1976d2;
  }
  /* 自定义进度条样式 */
  .progress-bar {
    width: 100%;
    height: 20px;
    background-color: #f3f3f3;
    border-radius: 10px;
    overflow: hidden;
    margin-top: 10px;
  }

  .progress {
    height: 100%;
    background-color: #4caf50;
    transition: width 0.3s ease; /* 平滑过渡效果 */
  }
</style>
